package org.huzhp.console.entity.vo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.huzhp.console.entity.GatewayRoute;
import org.springframework.beans.BeanUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: GatewayRouteVo
 * @Author: huzp
 * @CreateDate: 2020/3/12 15:37
 * @Version: 1.0
 */
@Data
public class GatewayRouteVo {

    private Long id;

    private String routeId;

    private String routeUri;

    private int routeOrder;

    private String routeMetadata;

    private Map routeMetadataMap;

    private List<GatewayPredicateVo> predicates;

    private List<GatewayFilterVo> filters;

    public GatewayRoute build() {
        if (this == null) {
            return null;
        }
        GatewayRoute route = new GatewayRoute();
        BeanUtils.copyProperties(this, route);
        route.setCreate_time(new Date());
        return route;
    }

    public Object buildGatewayJson() {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(buildGateway());
        } catch (JsonProcessingException e) {

        }
        return null;
    }

    public Object buildGateway() {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> jsonMap = new HashMap<>(6);
        jsonMap.put("id", this.routeId);
        jsonMap.put("uri", this.routeUri);
        jsonMap.put("order", this.routeOrder);
        jsonMap.put("predicates", this.predicates.stream().map(predicateVo -> predicateVo.buildGatewayJson()).collect(Collectors.toList()));
        jsonMap.put("filters", this.filters.stream().map(predicateVo -> predicateVo.buildGatewayJson()).collect(Collectors.toList()));

        if (StringUtils.isNotEmpty(this.routeMetadata)) {
            try {
                jsonMap.put("metadata", mapper.readValue(this.routeMetadata, Map.class));
            } catch (JsonProcessingException e) {

            }
        }
        return jsonMap;

    }
}
